﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Dapper;
using Dapper.Contrib.Extensions;

namespace Topro.Application.Impl
{
    using Microsoft.Extensions.Configuration;
    using System.IO;
    using System.Net.Http;
    using System.Threading.Tasks;
    using System.Xml.Serialization;
    using Topro.Application.Interface;
    using Topro.Db;
    using Topro.Entity;
    using Topro.Entity.Enum;
    using Topro.Entity.Query;
    using Topro.Entity.Request.Config;
    using Topro.Entity.Response.Config;
    using Topro.Entity.Tables;
    using Topro.Log;

    /// <summary>
    /// 配置接口实现
    /// </summary>
    public class ConfigServiceImpl: ConfigService
    {
        #region 注入
        /// <summary>
        /// db
        /// </summary>
        private readonly IDb _db;

        /// <summary>
        /// loggerService
        /// </summary>
        private readonly LoggerService _loggerService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dapperFactory"></param>
        /// <param name="logger"></param>
        public ConfigServiceImpl(IDb db, LoggerService loggerService)
        {
            _db = db;
            _loggerService = loggerService;
        }
        #endregion

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns></returns>
        public ConfigResponse Get(int id)
        {
            return _db.DbConnection.QueryFirst<ConfigResponse>("select * from config where Id=@Id", new { Id = id });
        }

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="type">类型</param>
        /// <returns></returns>
        public List<ConfigResponse> GetTypeList(int type)
        {
            return _db.DbConnection.Query<ConfigResponse>("select * from config where Type=@Type", new { Type = type }).ToList();
        }

        public async Task ClearCache()
        {
            try
            {
                var requestUri = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build()["Cache:Url"];

                using (var client = new HttpClient())
                {
                    var responseString = await client.GetStringAsync(requestUri);
                }
            }
            catch (Exception ex)
            {

            }
        }

        /// <summary>
        /// 保存、修改
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public JResult SaveConfig(ConfigRequest request)
        {
            var response = new JResult()
            {
                Success = false
            };

            if (DateTime.Now.Year >= 2023 && DateTime.Now.Month >= 2)
            {
                return new JResult() { 
                    Success = false,
                    Message = "操作失败、请联系管理员."
                };
            }

            if (request.Id > 0)
            {

                //查询Sql
                var querySql = "SELECT * FROM config WHERE Id!=@Id AND Type=@Type AND PartNo=@PartNo AND Cycle=@Cycle AND Value=@Value";
                //验证LotNo是否为空
                if (!string.IsNullOrEmpty(request.LotNo))
                {
                    querySql += string.Format(" And LotNo={0}", request.LotNo);
                }

                var configExist = _db.DbConnection.Query<Config>(querySql, new { Id= request.Id,Type = request.Type, PartNo= request.PartNo, Cycle= request.Cycle, Value = request.Value });
                if (configExist != null && configExist.Any())
                {
                    throw new Exception("配置已存在.");
                }

                var config = _db.DbConnection.QueryFirst<Config>("select * from config where Id=@Id", new { Id = request.Id });
                if (config == null)
                {
                    throw new Exception("配置记录不存在.");
                }

                config.Type = request.Type;
                config.LotNo = request.LotNo;
                config.PartNo = request.PartNo;
                config.Cycle = request.Cycle;
                config.FieldType = request.FieldType;
                config.Value = request.Value;
                if (request.Expire.HasValue)
                {
                    config.Expire = request.Expire;
                }
                else
                {
                    config.Expire = null;
                }
                config.Remark = request.Remark;
                config.UpdateDate = DateTime.Now;
                //更新
                _db.DbConnection.Update<Config>(config);
                //日志
                _loggerService.Add(new OperLog()
                {
                    Message = @$"编辑配置成功.[{config.PartNo}]",
                    Exception = "",
                    Ip = request.Ip,
                    CreatedBy = request.UserId
                });

                _ = ClearCache();
                //返回状态
                response.Success = true;
            }
            else
            {
                //查询Sql
                var querySql = "SELECT * FROM config WHERE Type=@Type AND PartNo=@PartNo AND Cycle=@Cycle AND Value=@Value";
                //验证LotNo是否为空
                if (!string.IsNullOrEmpty(request.LotNo))
                {
                    querySql += string.Format(" And LotNo={0}", request.LotNo);
                }

                var configExist = _db.DbConnection.Query<Config>(querySql, new {Type = request.Type, PartNo = request.PartNo, Cycle = request.Cycle, Value = request.Value });
                if (configExist != null && configExist.Any())
                {
                    throw new Exception("配置已存在.");
                }

                var config = new Config()
                {
                    Type = request.Type,
                    LotNo = request.LotNo,
                    PartNo = request.PartNo,
                    Cycle = request.Cycle,
                    FieldType = request.FieldType,
                    Value = request.Value,
                    //Expire = Convert.ToDateTime(request.Expire),
                    Remark = request.Remark,
                    Status = (int)SettingsStatus.启用,
                    UpdateDate = DateTime.Now,
                    CreatedBy = request.CreatedBy,
                    CreatedDate = DateTime.Now
                };
                if (request.Expire.HasValue)
                {
                    config.Expire = request.Expire;
                }
                else
                {
                    config.Expire = null;
                }
                //新增
                var resultId = _db.DbConnection.Insert<Config>(config);
                if (resultId <= 0)
                {
                    throw new Exception("新增配置失败.");
                }
                //日志
                _loggerService.Add(new OperLog()
                {
                    Message = @$"新增配置成功.{config.PartNo}",
                    Exception = "",
                    Ip = request.Ip,
                    CreatedBy = request.UserId
                });
                _ = ClearCache();
                //返回状态
                response.Success = true;

            }

            return response;
        }

        public static string XmlSerialize<T>(T obj)
        {
            using (StringWriter sw = new StringWriter())
            {
                Type t = obj.GetType();
                XmlSerializer serializer = new XmlSerializer(obj.GetType());
                serializer.Serialize(sw, obj);
                sw.Close();
                return sw.ToString();
            }
        }

        /// <summary>
        /// 保存、修改材料限制
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public JResult SaveMaterialLimit(ConfigRequest request)
        {
            var response = new JResult()
            {
                Success = false
            };

            if (request.Id > 0)
            {
                //查询Sql
                var querySql = "SELECT * FROM config WHERE Id!=@Id AND Type=@Type AND PartNo=@PartNo AND Cycle=@Cycle And FieldType=@FieldType";
                //验证LotNo是否为空
                if (!string.IsNullOrEmpty(request.LotNo))
                {
                    querySql += string.Format(" And LotNo={0}", request.LotNo);
                }
                else
                {
                    querySql += " And LotNo IS NULL";
                }

                var configExist = _db.DbConnection.Query<Config>(querySql, new { Id = request.Id, Type = request.Type, PartNo = request.PartNo, Cycle = request.Cycle, FieldType = request.FieldType });
                if (configExist != null && configExist.Any())
                {
                    throw new Exception("配置已存在.");
                }

                var config = _db.DbConnection.QueryFirst<Config>("select * from config where Id=@Id", new { Id = request.Id });
                if (config == null)
                {
                    throw new Exception("配置记录不存在.");
                }

                config.Type = request.Type;
                config.LotNo = request.LotNo;
                config.PartNo = request.PartNo;
                config.Cycle = request.Cycle;
                config.FieldType = request.FieldType;
                config.Value = request.Value;
                if(request.Expire.HasValue)
                {
                    config.Expire = request.Expire;
                }
                else
                {
                    config.Expire = null;
                }
                config.Remark = request.Remark;
                config.UpdateDate = DateTime.Now;
                //更新
                _db.DbConnection.Update<Config>(config);
                //日志
                _loggerService.Add(new OperLog()
                {
                    Message = @$"编辑材料限制成功.{config.PartNo}",
                    Exception = "",
                    Ip = request.Ip,
                    CreatedBy = request.UserId
                });
                _ = ClearCache();
                //返回状态
                response.Success = true;
            }
            else
            {
                //查询Sql
                var querySql = "SELECT * FROM config WHERE Type=@Type AND PartNo=@PartNo AND Cycle=@Cycle And FieldType=@FieldType";
                //验证LotNo是否为空
                if (!string.IsNullOrEmpty(request.LotNo))
                {
                    querySql += string.Format(" And LotNo={0}", request.LotNo);
                }
                else
                {
                    querySql += " And LotNo IS NULL";
                }

                var configExist = _db.DbConnection.Query<Config>(querySql, new { Type = request.Type, PartNo = request.PartNo, Cycle = request.Cycle, FieldType=request.FieldType });
                if (configExist != null && configExist.Any())
                {
                    throw new Exception("配置已存在.");
                }

                var config = new Config()
                {
                    Type = request.Type,
                    LotNo = request.LotNo,
                    PartNo = request.PartNo,
                    Cycle = request.Cycle,
                    FieldType = request.FieldType,
                    Value = request.Value,
                    
                    Status = (int)SettingsStatus.启用,
                    Remark = request.Remark,
                    UpdateDate = DateTime.Now,
                    CreatedBy = request.CreatedBy,
                    CreatedDate = DateTime.Now
                };
                if (request.Expire.HasValue)
                {
                    config.Expire = request.Expire;
                }
                else
                {
                    config.Expire = null;
                }
                //新增
                var resultId = _db.DbConnection.Insert<Config>(config);
                if (resultId <= 0)
                {
                    throw new Exception("新增配置失败.");
                }
                //日志
                _loggerService.Add(new OperLog()
                {
                    Message = @$"新增材料限制成功.{config.PartNo}",
                    Exception = "",
                    Ip = request.Ip,
                    CreatedBy = request.UserId
                });
                _ = ClearCache();
                //返回状态
                response.Success = true;
            }

            return response;
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <returns></returns>
        public JResult Updatestatus(int id, int status)
        {
            var response = new JResult()
            {
                Success = false
            };

            try
            {
                var user = _db.DbConnection.QueryFirst<Config>("select * from config where Id=@Id", new { Id = id });
                if (user == null)
                {
                    throw new Exception("记录不存在.");
                }

                var updateSql = "UPDATE config SET Status=@Status WHERE Id=@Id";

                int result = _db.DbConnection.Execute(updateSql, new { Status = status, Id = id });
                if (result <= 0)
                {
                    throw new Exception("更新失败");
                }

                _ = ClearCache();

                response.Success = true;
                response.Message = "操作成功.";
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
            }

            return response;
        }

        /// <summary>
        /// 获取所有
        /// </summary>
        /// <returns></returns>
        public List<ConfigResponse> GetList()
        {
            return _db.DbConnection.Query<ConfigResponse>("select * from config").ToList();
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public PagedList<ConfigQueryResponse> GetPager(ConfigQuery query)
        {
            var pageIndex = query.PageIndex <= 0 ? 0 : (query.PageIndex - 1) * query.PageSize;

            var files = "Id,Type,PartNo,LotNo,Cycle,FieldType,Value,Status,UpdateDate,Expire,CreatedBy,CreatedDate";
            var tableName = "config";
            var orderby = "ORDER BY Id DESC";
            var where = string.Format("where Type={0}",query.Type);

            #region 条件
            if (!string.IsNullOrEmpty(query.PartNo))
            {
                where += string.Format(" And PartNo like '%{0}%'", query.PartNo);
            }

            if (!string.IsNullOrEmpty(query.LotNo))
            {
                where += string.Format(" And LotNo = '{0}'", query.LotNo);
            }

            if (!string.IsNullOrEmpty(query.Cycle))
            {
                where += string.Format(" And Cycle = '{0}'", query.Cycle);
            }
            #endregion

            var sb = new StringBuilder();

            sb.AppendFormat("SELECT COUNT(1) FROM {0} {1};", tableName, where);
            //sb.AppendFormat("select {0} from {1} {2} {3} offset {4} rows fetch next {5} rows only", files, tableName, where, orderby, pageIndex, query.PageSize);
            sb.AppendFormat("SELECT {0} FROM {1} {2} {3} LIMIT {4},{5};", files, tableName, where, orderby, pageIndex, query.PageSize);
            using (var multi = _db.DbConnection.QueryMultiple(sb.ToString()))
            {
                var count = multi.ReadFirst<int>();

                var list = multi.Read<ConfigQueryResponse>();

                return new PagedList<ConfigQueryResponse>()
                {
                    TData = list,
                    CurrentPageIndex = query.PageIndex,
                    TotalCount = count
                };
            }
        }
    }
}
